package com.thunder.soft.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.thunder.soft.MusicService;
import com.thunder.soft.R;
import com.thunder.soft.common.base.BaseBean;
import com.thunder.soft.common.base.BaseFragment;
import com.thunder.soft.common.util.BitmapUtils;
import com.thunder.soft.common.util.CameraUtils;
import com.thunder.soft.common.util.SharedPreferenceUtils;
import com.thunder.soft.common.util.ViewModelProviderHelper;
import com.thunder.soft.databinding.FragmentPersonBinding;
import com.thunder.soft.ui.activity.LoginActivity;
import com.thunder.soft.ui.activity.MainActivity;
import com.thunder.soft.vm.PersonViewModel;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

public class PersonFragment extends BaseFragment<FragmentPersonBinding> {

    private static String TAG = PersonFragment.class.getName();
    private PersonViewModel viewModel;
    private Intent intent;
    //底部弹窗
    private BottomSheetDialog bottomSheetDialog;
    //弹窗视图
    private View bottomView;
    //存储拍完照后的图片
    private File outputImagePath;
    //启动相机标识
    public static final int TAKE_PHOTO = 1;
    //启动相册标识
    public static final int SELECT_PHOTO = 2;
    //权限请求
    private RxPermissions rxPermissions;
    //是否拥有权限
    private boolean hasPermissions = false;
    //图片控件
    private ImageView ivHead;
    //Base64
    private String base64Pic;
    //拍照和相册获取图片的Bitmap
    private Bitmap orc_bitmap;

    //Glide请求图片选项配置
    private RequestOptions requestOptions = RequestOptions.circleCropTransform()
            .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
            .skipMemoryCache(true);//不做内存缓存

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkVersion();
        viewModel = ViewModelProviderHelper.buildViewModel(this, PersonViewModel.class);
        getLifecycle().addObserver(viewModel);
        viewModel.register(getContext());

        Intent intent = new Intent(getContext(), MusicService.class);
        getContext().startService(intent);
    }

    @Override
    protected void initData() {
        binding.setViewModel(viewModel);
        ivHead = binding.ivAvatar;
        binding.tvName.setText(SharedPreferenceUtils.getInstance().get(getContext(), "username", "username").toString());
        binding.tvId.setText("ID:" + SharedPreferenceUtils.getInstance().get(getContext(), "id", "666666").toString());
        Glide.with(this).load(SharedPreferenceUtils.getInstance().get(getContext(), "imageUrl",
                        "https://dss0.bdstatic.com/6Ox1bjeh1BF3odCf/it/u=572734183,263400261&fm=74&app=80&f=JPEG?w=200&h=200"))
                .apply(requestOptions)
                .into(ivHead);

        viewModel.getErrorMsg().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
            }
        });

        viewModel.getLiveData().observe(this, new Observer<BaseBean<Object>>() {
            @Override
            public void onChanged(BaseBean<Object> objectBaseBean) {
                intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            }
        });

        viewModel.getImageLiveData().observe(this, new Observer<View>() {
            @Override
            public void onChanged(View view) {
                bottomSheetDialog = new BottomSheetDialog(getContext());
                bottomView = getLayoutInflater().inflate(R.layout.dialog_bottom, null);
                bottomSheetDialog.setContentView(bottomView);
                TextView tvTakePictures = bottomView.findViewById(R.id.tv_take_pictures);
                TextView tvOpenAlbum = bottomView.findViewById(R.id.tv_open_album);
                TextView tvCancel = bottomView.findViewById(R.id.tv_cancel);

                //拍照
                tvTakePictures.setOnClickListener(v -> {
                    takePhoto();
                    showMsg("拍照");
                    bottomSheetDialog.cancel();
                });

                //打开相册
                tvOpenAlbum.setOnClickListener(v -> {
                    openAlbum();
                    showMsg("打开相册");
                    bottomSheetDialog.cancel();
                });

                //取消
                tvCancel.setOnClickListener(v -> {
                    bottomSheetDialog.cancel();
                });

                bottomSheetDialog.show();
            }
        });

        viewModel.getLanguageLiveData().observe(this, new Observer<View>() {
            @Override
            public void onChanged(View view) {
                bottomSheetDialog = new BottomSheetDialog(getContext());
                bottomView = getLayoutInflater().inflate(R.layout.dialog_bottom_language, null);
                bottomSheetDialog.setContentView(bottomView);
                TextView tvZh = bottomView.findViewById(R.id.tv_zh);
                TextView tvEn = bottomView.findViewById(R.id.tv_en);
                TextView tvCancel = bottomView.findViewById(R.id.tv_cancel);

                //简体中文
                tvZh.setOnClickListener(v -> {
                    Locale.setDefault(Locale.CHINESE);
                    Configuration config = getContext().getResources().getConfiguration();
                    config.locale = Locale.CHINESE;
                    getContext().getResources().updateConfiguration(config
                            , getContext().getResources().getDisplayMetrics());
                    refreshSelf();
                    showMsg("切换至简体中文");
                    bottomSheetDialog.cancel();
                });

                //英文
                tvEn.setOnClickListener(v -> {
                    Locale.setDefault(Locale.ENGLISH);
                    Configuration config = getContext().getResources().getConfiguration();
                    config.locale = Locale.ENGLISH;
                    getContext().getResources().updateConfiguration(config
                            , getContext().getResources().getDisplayMetrics());
                    refreshSelf();
                    showMsg("切换至英文");
                    bottomSheetDialog.cancel();
                });

                //取消
                tvCancel.setOnClickListener(v -> {
                    bottomSheetDialog.cancel();
                });

                bottomSheetDialog.show();
            }
        });

        viewModel.getMusicLiveData().observe(this, new Observer<View>() {
            @Override
            public void onChanged(View view) {
                boolean isSelected = binding.ivMusic.isSelected();
                binding.ivMusic.setSelected(!binding.ivMusic.isSelected());
                Intent intent =new Intent("CONTROL");
                if (isSelected){//正在播放
                    intent.putExtra("control",0);
                }else {//未播放
                    intent.putExtra("control",1);
                }
                getContext().sendBroadcast(intent);
            }
        });


        viewModel.getActivityLiveData().observe(this, new Observer<Map<String, Object>>() {
            @Override
            public void onChanged(Map<String, Object> value) {
                intent = new Intent(getActivity(), (Class<?>) value.get("activity"));
                startActivity(intent);
            }
        });
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_person;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //拍照后返回
            case TAKE_PHOTO:
                if (resultCode == getActivity().RESULT_OK) {
                    //显示图片
                    displayImage(outputImagePath.getAbsolutePath());
                }
                break;
            //打开相册后返回
            case SELECT_PHOTO:
                if (resultCode == getActivity().RESULT_OK) {
                    String imagePath = null;
                    //判断手机系统版本号
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                        //4.4及以上系统使用这个方法处理图片
                        imagePath = CameraUtils.getImageOnKitKatPath(data, getContext());
                    } else {
                        imagePath = CameraUtils.getImageBeforeKitKatPath(data, getContext());
                    }
                    //显示图片
                    displayImage(imagePath);
                }
                break;
            default:
                break;
        }
    }

    public void refreshSelf() {
        Intent intent = new Intent(getContext(), MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void showMsg(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @SuppressLint("CheckResult")
    private void checkVersion() {
        //Android6.0及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            rxPermissions = new RxPermissions(getActivity());
            //权限请求
            rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(granted -> {
                        if (granted) {//申请成功
                            hasPermissions = true;
                        } else {//申请失败
                            showMsg("权限未开启");
                            hasPermissions = false;
                        }
                    });
        } else {
            //Android6.0以下
            showMsg("无需请求动态权限");
        }
    }

    private void takePhoto() {
        if (!hasPermissions) {
            showMsg("未获取到权限");
            checkVersion();
            return;
        }

        SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String filename = timeStampFormat.format(new Date());
        outputImagePath = new File(getContext().getExternalCacheDir(),
                filename + ".jpg");
        Intent takePhotoIntent = CameraUtils.getTakePhotoIntent(getContext(), outputImagePath);
        startActivityForResult(takePhotoIntent, TAKE_PHOTO);
    }

    private void openAlbum() {
        if (!hasPermissions) {
            showMsg("未获取到权限");
            checkVersion();
            return;
        }
        startActivityForResult(CameraUtils.getSelectPhotoIntent(), SELECT_PHOTO);
    }

    private void displayImage(String imagePath) {
        if (!TextUtils.isEmpty(imagePath)) {

            SharedPreferenceUtils.getInstance().put(getContext(), "imageUrl", imagePath);
            Glide.with(this).load(imagePath).apply(requestOptions).into(ivHead);
            orc_bitmap = CameraUtils.compression(BitmapFactory.decodeFile(imagePath));
            base64Pic = BitmapUtils.bitmapToBase64(orc_bitmap);
        } else {
            showMsg("图片获取失败");
        }
    }
}